import argparse
import importlib
import sys
import traceback

from flask_script import Command


class MovieJob(Command):
    capture_all_args = True

    def run(self, *args, **kwargs):
        args = sys.argv[2:]
        parser = argparse.ArgumentParser(add_help=True)
        parser.add_argument("-m", "--name", dest="name", metavar="name", help="指定的Job名", required=True)
        parser.add_argument("-a", "--act", dest="act", metavar="act", help="Job动作", required=False)
        parser.add_argument("-p", "--param", dest="param", metavar="param", nargs="*", help="业务参数", required=False)
        params = parser.parse_args(args)
        params_dict = params.__dict__
        print(params_dict)
        if "name" not in params_dict or not params_dict["name"]:
            return self.tips()
        try:
            '''
            from jobs.tasks.test import JobTask
            '''
            module_name = params_dict["name"].replace("/", '.')
            import_string = "jobs.tasks.%s" % module_name
            # print(import_string)
            target = importlib.import_module(import_string)
            exit(target.JobTask().run(params_dict))
        except Exception as e:
            traceback.print_exc()
        return

    def tips(self):
        tip_msg = '''
            请正确的调度 job
            '''
        print(tip_msg)
        return
